package com.szlanyou.thirdsdk.retrofit.interceptor;

import android.text.TextUtils;
import android.util.Log;

import com.szlanyou.thirdsdk.retrofit.callback.FileUploadProgressHttpResultHandlerHolder;
import com.szlanyou.thirdsdk.retrofit.file.upload.ProgressRequestBody;
import com.szlanyou.thirdsdk.retrofit.file.upload.ProgressRequestListener;
import com.szlanyou.thirdsdk.retrofit.file.upload.UploadFileService;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;
import com.szlanyou.thirdsdk.retrofit.util.RequestBodyUtil;
import com.szlanyou.thirdsdk.retrofit.util.TimeCountHelper;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;

import okhttp3.Interceptor;
import okhttp3.Request;
import okio.Buffer;
import okio.BufferedSource;

/**
 * author:@author 陈章 on 2016/6/21 0021.
 * des:
 * 拦截上传文件进度过滤器
 */
public class RequestProgressInterceptor implements Interceptor {
    private static final String TAG = "RequestProgressIntercep";
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request orgRequest = chain.request();
        String method = orgRequest.method();
        if(method.equalsIgnoreCase(ShareInfoHelper.METHOD_POST) && !FileUploadProgressHttpResultHandlerHolder.isEmpty()){
            String headerUniqueRequestId = orgRequest.header(UploadFileService.HEADER_KEY_UNIQUE_REQUEST_ID);
            /**只有{@link UploadFileService}才有这个自定义的头字段*/
            if(!TextUtils.isEmpty(headerUniqueRequestId)){
                Request request = orgRequest.newBuilder()
                        .method(method, new ProgressRequestBody(orgRequest.url().toString(), orgRequest.body(), new ProgressRequestListener() {
                            @Override
                            public void onRequestProgress(String url, long bytesWritten, long contentLength) {
                                FileUploadProgressHttpResultHandlerHolder.onRequestProgress(headerUniqueRequestId,url,bytesWritten,contentLength);
                            }
                        }))
                        .build();
                return chain.proceed(request);
            }
        }
        return chain.proceed(orgRequest);
    }
}
